package middleware

import (
	"net/http"
	"time"

	"gitee.com/LangHuaHuachihua/cloud-gin-manager/serializer"
	"gitee.com/LangHuaHuachihua/cloud-gin-manager/utils"
	"github.com/gin-gonic/gin"
)

func JwtToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		//得到token
		tokenHeard := c.Request.Header.Get("Authorization")
		if tokenHeard == "" {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}

		token, err := utils.CheckToken(tokenHeard)
		if err != nil {
			c.JSON(200, serializer.TokenGetCheck())
			c.Abort()
			return
		}
		//判断token是否过期
		if time.Now().Unix() > token.ExpiresAt.Unix() {
			c.JSON(http.StatusOK, serializer.TokenGetCheck())
			c.Abort()
			return
		}
		c.Set("username", token.Username)
		c.Set("Id", token.ID)
		c.Next()
	}
}
